Expression and Statement
In JavaScript:
- Expression produces a value.
- Statement performs an action.
Expression
A valid unit of code that resolves to a value.
- Simple values:
5,"hello",true - Variables:
x,y - Operations:
x + 2,Math.max(1, 2) - Functions stored in variables (function expressions)
Function Expression
A function assigned to a variable is a function expression.
const greet = () => {
console.log("Hello!");
};
- Stored in a variable (
var,let, orconst). - Can produce a value (the function itself) that can be passed around.
- Can be anonymous or named.
Statement (Declaration)
A complete unit of execution that performs an action but may not return a value.
- Variable declarations:
let x = 5; - Conditional statements:
if(x < 4) { ... } - Loops:
for(let i=0; i<5; i++) { ... } - Function declarations (statements)
Function Statment
A function declared using the function keyword without being assigned to a variable is a statement.
function greet() {
console.log("Hello!");
}
- Called a function declaration.
- Executes an action when invoked.
- Does not produce a value that can be assigned.
Expressoin vs Statement
| Feature | Expression | Statement |
|---|---|---|
| Produces Value | ✅ Yes | ❌ Usually no |
| Can be Assigned | ✅ Yes | ❌ No |
| Example | 5, x + 2, const f = () => {} | let x = 5;, if(x<4){}, function f(){} |